package com.feri.fc.handler;

import com.feri.fc.vo.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/26 11:09
 * @Modified:
 */
@ControllerAdvice
public class HandleException {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handleValidationExceptions(MethodArgumentNotValidException ex) {
        List<ObjectError> errors=ex.getAllErrors();
        List<Map<String,String>> result=new ArrayList<>();

        errors.forEach(e->{
            HashMap<String,String> field=new HashMap<>();
            field.put("field",e.getCode());
            field.put("msg",e.getDefaultMessage());
            result.add(field);
        });

        if(errors!=null && errors.size()>0){
            return R.fail(result);
        }
        return R.fail("参数校验失败，请检查！");
    }
}
